<?php


class JoinForm extends CFormModel {
	
	public $username;
	public $password;
	public $password_check;
	public $email;
	public $first_name;
	public $last_name;
	public $phone_number;
	public $initials;
	public $language;
	public $gender;
	public $birth_date;
	public $address1;
	public $address2;
	public $address3;
	public $city_id;
	
	public function __construct() {
		parent::__construct();
		$record = Yii::app()->user->getState('dbuser');
		if ($record != null) {
			$this->username = $record->username;
			$this->email = $record->email;
			$this->language = $record->language;
			$this->first_name = $record->first_name;
			$this->last_name = $record->last_name;
			$this->phone_number = $record->phone_number;
			$this->initials = $record->initials;
			$record = $this->findUserByInitials($record->initials);
		}
		
		if ($record != null) {
			$this->gender = $record->gender;
			$this->birth_date = $record->birth_date;
			$this->address1 = $record->address1;
			$this->address2 = $record->address2;
			$this->address3 = $record->address3;
			$this->city_id = $record->city_id;
		}
	}

	/**
	 * Declares the validation rules.
	 * The rules state that username and password are required,
	 * and password needs to be authenticated.
	 */
	public function rules() {
		return array (
			array ('email, language, first_name, password, initials, gender, birth_date, city_id', 'required'),
			array ('email', 'email'),
		);
	}

	/**
	 * Declares attribute labels.
	 */
	public function attributeLabels() {
		return array (
			'password_new' => Yii::t('userinfo', 'Type your new password'),
			'password_check' => Yii::t('userinfo', 'Type your password again'),
			'email' => Yii::t('userinfo', 'Email address'),
			'language' => Yii::t('languages', 'Language'),
			'email' => Yii::t('user', 'Mail address'),
			'roles' => Yii::t('user', 'Roles'),
			'first_name' => Yii::t('user', 'First Name'),
			'last_name' => Yii::t('user', 'Last Name'),
			'phone_number' => Yii::t('user', 'Phone Number'),
			'initials' => Yii::t('user', 'Initials'),
			'gender' => Yii::t('database', 'Gender'),
			'birth_date' => Yii::t('database', 'Birth Date'),
			'address1' => Yii::t('database', 'Address1'),
			'address2' => Yii::t('database', 'Address2'),
			'address3' => Yii::t('database', 'Address3'),
			'city_id' => Yii::t('database', 'City'),
			'username' => Yii::t('database', 'Username')
		);
	}

	public function save() {
		$record = $this->findUserByInitials($this->initials);
		if ($record != null) {
			$this->addError('initials', Yii::t('userinfo', 'A user with same initials already exists'));
		}
	
		$record = $this->findUserByUsername($this->username);
		if ($record != null) {
			$this->addError('username', Yii::t('userinfo', 'Username already exists'));
		}
	
		if (!$this->hasErrors()) // we only want to authenticate when no input errors
		{
			// 1st begin a transaction
			$transaction = Yii::app()->db->beginTransaction();
			
			$user = new User();
			$user->username = $this->username;
			$user->password = md5($this->password);
			$user->email = $this->email;
			$user->language = $this->language;
			$user->first_name = $this->first_name;
			$user->last_name = $this->last_name;
			$user->phone_number = $this->phone_number;
			$user->initials = $this->initials;
			$user->simulation = true;
			$user->save();
			
			if ($user->hasErrors()) {
				$this->addErrors($user->errors);
				$transaction->rollBack();
				return false;
			}
			
			$owner = new Owner();
			$owner->first_name = $this->first_name;
			$owner->last_name = $this->last_name;
			$owner->gender = $this->gender;
			$owner->birth_date = $this->birth_date;
			$owner->address1 = $this->address1;
			$owner->address2 = $this->address2;
			$owner->address3 = $this->address3;
			$owner->city_id = $this->city_id;
			$owner->email = $this->email;
			$owner->phone_number = $this->phone_number;
			$owner->referent = $user->getFullName();
			$owner->adviser_initials = $this->initials;
			
			if ($this->isEmpty($owner->city_id)) {
				$cities = $this->findCities(strtoupper($_POST['city_id']), 1);
				if ($cities != null && count($cities) > 0)
				$owner->city_id = $cities[0]->id;
			}
			
			$owner->save();
			if ($owner->hasErrors()) {
				$this->addErrors($owner->errors);
				$transaction->rollBack();
				return false;
			}
			
			$identity = new UserIdentity($this->username, $this->password);
			$identity->authenticate();
			switch ($identity->errorCode) {
				case UserIdentity::ERROR_NONE :
					// Changing mail address
					$transaction->rollBack();
					Yii::app()->user->setState('dbuser', $identity->getUser());
					$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
					Yii::app()->user->login($this->_identity,$duration);
					CVarDumper::dump(Yii::app()->user, 10, true);
					break;
				case UserIdentity::ERROR_USERNAME_INVALID :
					Yii::app()->user->logout();
					$transaction->rollBack();
					$this->addError('username', Yii::t('userinfo', 'Unable to logged in'));
					break;
				default : // UserIdentity::ERROR_PASSWORD_INVALID
					$transaction->rollBack();
					$this->addError('password', Yii::t('userinfo', 'Current password is incorrect.'));
					break;
			}
		}
		
		return !$this->hasErrors();
	}
	
	protected function findCities($name, $limit) {
		$criteria = new CDbCriteria;
		$criteria->condition = "city_name LIKE :sterm or postal_code  LIKE :sterm ";
		$criteria->params = array (
			":sterm" => "$name%"
		);
		$criteria->limit = $limit;
		return City::model()->findAll($criteria);
	}
	
	protected function findUserByInitials($initials) {
		return User::model()->find("initials = :initials", array(":initials" => $initials));
	}

	protected function findUserByUsername($username) {
		return User::model()->findByPk($username);
	}

	public function isEmpty($value, $trim = false) {
		return $value === null || $value === array () || $value === '' || $trim && !is_array($value) && trim($value) === '';
	}

}

